#!/bin/sh

PATH=/bin:/sbin:/usr/bin:/usr/sbin
export PATH

#
# Create karabiner_machine_identifier
#

if [ ! -f '/Library/Application Support/org.pqrs/tmp/karabiner_machine_identifier.json' ]; then
    echo "{\"karabiner_machine_identifier\": \"krbn-$(uuidgen | tr '[:upper:]' '[:lower:]')\"}" |
        tee '/Library/Application Support/org.pqrs/tmp/karabiner_machine_identifier.json'
    chmod 0644 '/Library/Application Support/org.pqrs/tmp/karabiner_machine_identifier.json'
fi

#
# Set suid
#

chmod 4755 '/Library/Application Support/org.pqrs/Karabiner-Elements/bin/karabiner_session_monitor'

#
# Set icon
#

'/Library/Application Support/org.pqrs/Karabiner-Elements/Karabiner-AppIconSwitcher.app/Contents/MacOS/Karabiner-AppIconSwitcher'

#
# Relaunch karabiner processes
#

killall karabiner_grabber
killall karabiner_session_monitor
killall karabiner_console_user_server
killall Karabiner-Menu
killall Karabiner-MultitouchExtension
killall Karabiner-NotificationWindow

#
# Update version file
#

cp \
    '/Library/Application Support/org.pqrs/Karabiner-Elements/package-version' \
    '/Library/Application Support/org.pqrs/Karabiner-Elements/version'

#
# Create a backup to allow recovery if the user manually deletes Karabiner-Elements without using the uninstaller
#

tar -C /Applications -cf '/Library/Application Support/org.pqrs/Karabiner-Elements/Karabiner-Elements.app.tar.gz' Karabiner-Elements.app

exit 0
